#coding=UTF8
import html
import re

def typograph(text):
    symb = {    
    ' - ' : ' &#8212; '    
    }
    
    for key, val in symb.items():
        text = text.replace(key, val)
    
    text = re.sub('"(.+?)"', '&laquo;\\1&raquo;', text)    

    
    return text

def display(text):
    if text:
        return text.replace('\n','<br>')


def make_title(data_in, is_utf = False, size = 60):
    if is_utf:
        data_in = data_in.decode('UTF-8')

    #data_in = data_in.lstrip() #обрезаем лишние пробелы в начале
    
    data_in = html.make_plain(data_in).lstrip()
    
    r = u'^([\S\s]{0,%s}\S)(?:\s|$)' % (size -1)
    
    re_rez = re.match(r, data_in, re.U )
    if re_rez:
        if re_rez.groups()[0] > 0:
            rez = re_rez.groups()[0]
    else:
        rez = data_in[:size].strip()
    
    #заменяем разные левые пробельные символы на пробелы (например переносы строк, табы..)
    rez = ' '.join( [c for c in rez.split() if c])

    if is_utf:
        rez = rez.encode('UTF-8')

    return rez


def make_plain(data_in, is_utf = True):
    return html.make_plain(data_in, is_utf = is_utf)


def make_simple_format(data_in, is_utf = False):
    return html.sanitize(data_in, is_utf = is_utf, allowed_elements = ['b', 'a', 'i', 'p', 'br'], allowed_attributes = ['href'])

def getWordFormForCount( count ):
    count = count % 100
    c10 = count % 10
    if c10 == 0 or c10 >= 5 or ( count > 5 and count < 21 ): return 0
    if c10 == 1: return 1
    return 2

def test_get_title():
    '''
        юнит-тесты для get_title
    '''
    assert make_title(u'&lt;&gt;') == u'&lt;&gt;'
    assert make_title(u'mam wash ram', size = 10) == u'mam wash'
    assert make_title(u'mamwashram', size = 10) == u'mamwashram'
    assert make_title(u's', size = 10) == u's'
    assert make_title(u'', size = 10) == u''
    assert make_title(u'mamamilaramuspivom', size = 10) == u'mamamilara'
    assert make_title(u'mamamilaramuspivom', size = 10) == u'mamamilara'
    assert make_title(u'm                     amamilaramuspivom', size = 10) == u'm'
    assert make_title(u' a b c d                    amamilaramuspivom', size = 10) == u'a b c d'
    assert make_title(u'!', size = 10) == u'!'
    assert make_title(u'! ?', size = 10) == u'! ?'
    assert make_title(u'! mama', size = 10) == u'! mama'
    assert make_title(u'! mamamilaramu', size = 10) == u'!'
    assert make_title(u' ! ? mamamilaramu', size = 10) == u'! ?'
    assert make_title(u' ! ', size = 10) == u'!'
    assert make_title(u'      ', size = 10) == u''
    assert make_title(u'a\na', size = 10) == u'a a'
    assert make_title(u'a\t\n a', size = 10) == u'a a'
    assert make_title(u'\t\n a\t\n a\t\n ', size = 10) == u'a a'
    
if __name__ == '__main__':
    print make_title(u'<script> local host </script>', size = 10)
    test_get_title()
